package com.lele.task;

import com.lele.constant.MailContant;
import com.lele.enums.MailEnums;
import com.lele.pojo.Employee;
import com.lele.pojo.MailLog;
import com.lele.service.IEmployeeService;
import com.lele.service.IMailLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class MailTask {
    @Resource
    private IMailLogService mailLogService;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private IEmployeeService employeeService;


    /**
     * 查询出那些投递中的，并且重试的时间已经到了的。
     * 如果重试的次数超过了三次，就将状态变为投递失败，不再重新发送
     * 重试的次数<=3的，继续投递。
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void mailTask(){
        log.error("定时任务执行");
        List<MailLog> mailLogList = mailLogService.lambdaQuery().eq(MailLog::getStatus, MailEnums.MESSAGE_DELIVERYING.getCode()).
                lt(MailLog::getTryTime, LocalDateTime.now()).list();
        if(mailLogList==null){
            return;
        }
        for (MailLog item : mailLogList) {
            //重试的次数超过了三次就设置状态为投递失败
            if(item.getCount()>=MailContant.COUNT) {
                mailLogService.lambdaUpdate().set(MailLog::getStatus, MailEnums.MESSAGE_FAILURE.getCode()).update();
                return;
            }
            //否则就对对应的重试次数+1并且重新投递
            mailLogService.lambdaUpdate().set(MailLog::getCount,item.getCount()+1)
                    .eq(MailLog::getMsgId,item.getMsgId()).update();
            Employee employee = employeeService.getById(item.getEid());
            rabbitTemplate.convertAndSend(MailContant.MAIL_EXCHANGE,MailContant.MAIL_ROUTER,employee,new CorrelationData(item.getMsgId()));
        }
        }
}
